package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.base.exception.Result;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.mapper.*;
import com.xuecheng.content.model.dto.BindTeachplanMediaDto;
import com.xuecheng.content.model.dto.SaveTeachplanDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.CourseTeacher;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.content.model.po.TeachplanMedia;
import com.xuecheng.content.service.TeachplanService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;


 @Service
public class TeachplanServiceImpl implements TeachplanService {

  @Autowired
 TeachplanMapper teachplanMapper;
  @Autowired
  TeachplanMediaMapper teachplanMediaMapper;
  @Autowired
  CourseBaseMapper courseBaseMapper;
  @Autowired
  CourseMarketMapper courseMarketMapper;
  @Autowired
  CourseTeacherMapper courseTeacherMapper;
 @Override
 public List<TeachplanDto> findTeachplanTree(long courseId) {
  return teachplanMapper.selectTreeNodes(courseId);
 }

 public Integer getTeachplanCount(Long courseId,Long parentId)
 {
  LambdaQueryWrapper<Teachplan> queryWrapper=new LambdaQueryWrapper();
  queryWrapper.eq(Teachplan::getCourseId,courseId).eq(Teachplan::getParentid,parentId).eq(Teachplan::getStatus,1);
  Integer count = teachplanMapper.selectCount(queryWrapper);
  return count+1;
 }
 @Override
 public void saveTeachplan(SaveTeachplanDto teachplanDto) {
  //根据id判断是新增还是修改
  Long id = teachplanDto.getId();
  if (id==null)
  {
   //新增
   Teachplan teachplan = new Teachplan();
   BeanUtils.copyProperties(teachplanDto,teachplan);
   //确认·orderby
   Long courseId = teachplanDto.getCourseId();
   Long parentid = teachplanDto.getParentid();
   Integer count = getTeachplanCount(courseId, parentid);
   teachplan.setOrderby(count);
   teachplanMapper.insert(teachplan);
  }
  else{
   //修改
   Teachplan teachplan = teachplanMapper.selectById(id);
   BeanUtils.copyProperties(teachplanDto,teachplan);
   teachplanMapper.updateById(teachplan);

  }

 }

 @Override
public Result deleteTeachplan(Long id) {
    Teachplan teachplan = teachplanMapper.selectById(id);
    Long parentid = teachplan.getParentid();
    if (parentid == 0) {  // 大章节
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getParentid, id);
        Integer count = teachplanMapper.selectCount(queryWrapper);
        if (count > 0) {
            return new Result(400, "120409", "课程计划信息还有子级信息，无法操作");
        } else {
            teachplanMapper.deleteById(id);
            return new Result(200);
        }
    } else { // 小章节直接删除媒资表
        teachplanMapper.deleteById(id);
        LambdaQueryWrapper<TeachplanMedia> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeachplanMedia::getTeachplanId, id);
        teachplanMediaMapper.delete(queryWrapper);
        return new Result(200);
    }
}

    @Override
    public void move(String moveType, Long id) {
     //获取到课程标识
        Teachplan teachplan = teachplanMapper.selectById(id);
        if (moveType.equals("moveup"))
        {
            adjustOrder(teachplan,true);

        }
        else if (moveType.equals("movedown"))
        {
            adjustOrder(teachplan,false);

        }
    }



    private void adjustOrder(Teachplan teachplan, boolean moveUp) {
        Long parentid = teachplan.getParentid();
        Long courseId = teachplan.getCourseId();
        Integer grade = teachplan.getGrade();
        Integer orderby = teachplan.getOrderby();

        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId, courseId)
                .eq(Teachplan::getParentid, parentid)
                .eq(Teachplan::getGrade, grade)
                .eq(Teachplan::getStatus, 1);

        if (moveUp) {
            queryWrapper.lt(Teachplan::getOrderby, orderby).orderByDesc(Teachplan::getOrderby);
        } else {
            queryWrapper.gt(Teachplan::getOrderby, orderby).orderByAsc(Teachplan::getOrderby);
        }
        queryWrapper.last("limit 1");

        Teachplan targetPlan = teachplanMapper.selectOne(queryWrapper);
        if (targetPlan == null) {
            throw new XueChengPlusException(moveUp ? "无法上移，当前课程计划已经是第一个" : "无法下移，当前课程计划已经是最后一个");
        }

        // 交换orderby值
        int tempOrderby = teachplan.getOrderby();
        teachplan.setOrderby(targetPlan.getOrderby());
        targetPlan.setOrderby(tempOrderby);

        teachplanMapper.updateById(teachplan);
        teachplanMapper.updateById(targetPlan);
    }


    @Override
    @Transactional
    public void deleteCourse(Long companyId, Long courseId) {
        //校验课程·id是否为空
        if (courseId == null) {
            XueChengPlusException.cast("课程id为空");
        }
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        Long companyId1 = courseBase.getCompanyId();
        if(!Objects.equals(companyId,companyId1))
        {
            XueChengPlusException.cast("只允许删除本机构的课程");
        }
        if (!courseBase.getAuditStatus().equals("202002"))
        {
             XueChengPlusException.cast("只允许删除未提交课程");
        }
        courseBaseMapper.deleteById(courseId);
        courseMarketMapper.deleteById(courseId);
        //删除课程计划
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId, courseId);
        teachplanMapper.delete(queryWrapper);
        //删除教师信息
        LambdaQueryWrapper<CourseTeacher> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(CourseTeacher::getCourseId, courseId);
        courseTeacherMapper.delete(queryWrapper1);
    }

    @Override
    @Transactional
    public TeachplanMedia associationMedia(BindTeachplanMediaDto bindTeachplanMediaDto) {

        Long teachplanId = bindTeachplanMediaDto.getTeachplanId();
        Teachplan teachplan = teachplanMapper.selectById(teachplanId);
        if (teachplan==null)
        {
            XueChengPlusException.cast("课程计划不存在");
        }
        Integer grade = teachplan.getGrade();
        if(grade!=2){
            XueChengPlusException.cast("只允许第二级教学计划绑定媒资文件");
        }

        //先删后插
        int delete = teachplanMediaMapper.delete(new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getTeachplanId, bindTeachplanMediaDto.getTeachplanId()));
        Long courseId = teachplan.getCourseId();
        TeachplanMedia teachplanMedia = new TeachplanMedia();
        BeanUtils.copyProperties(bindTeachplanMediaDto,teachplanMedia);
        teachplanMedia.setCourseId(courseId);
        teachplanMedia.setMediaFilename(bindTeachplanMediaDto.getFileName());
        teachplanMedia.setCreateDate(LocalDateTime.now());
        int insert = teachplanMediaMapper.insert(teachplanMedia);
        return teachplanMedia;
    }

    @Override
    public void deletebyteachPlanId(Long teachPlanId, String mediaId) {
     //判断teachPlanId和mediaId是否为空
        if (teachPlanId == null || mediaId == null) {
            XueChengPlusException.cast("参数为空");
        }
        teachplanMediaMapper.deletebyteachPlanId(teachPlanId, mediaId);
    }

    @Override
    public List<Teachplan> getBycourseId(Long courseId) {
        List<Teachplan> teachplan = teachplanMapper.selectBycourseId(courseId);
        return teachplan;
    }
}